package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    //条件+分页查询菜品数据
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {

        ArrayList<DishDTO> dtos = new ArrayList<>();

        Page<DishDTO> pageinfoDto = new Page(page, pageSize);

        //创建分页构造器对象
        Page<Dish> pageinfo = new Page(page, pageSize);

        //定义条件构造器 + 模糊查询的条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        //使用mp提供的分页查询方法
        dishService.page(pageinfo, wrapper);

        //BeanUtils工具  实现两个对象的数据复制
        //BeanUtils.copyProperties(pageinfo,pageinfoDto);

        //
        for (Dish record : pageinfo.getRecords()) {
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            DishDTO dishDTO = new DishDTO();
            dishDTO.setCategoryName(category.getName());
            BeanUtils.copyProperties(record, dishDTO);
            dtos.add(dishDTO);
        }

        pageinfoDto.setRecords(dtos);

        pageinfoDto.setTotal(pageinfo.getTotal());
        //返回page对象
        return R.success(pageinfoDto);

    }

    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDTO) {
        log.info(dishDTO.toString());
        dishService.savewithFlavor(dishDTO);  //在disServiceImpl中实现新增菜品方法

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("菜品添加成功");
    }


    //根据ID查询菜品信息  和对应的口味信息
    @GetMapping("/{id}")
    public R<DishDTO> get(@PathVariable Long id) {
        DishDTO dishDTO = dishService.getByIdwithFlavor(id);
        return R.success(dishDTO);
    }

    //修改菜品方法
    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO) {
        log.info(dishDTO.toString());
        dishService.updateWithFlavor(dishDTO);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    //删除菜品方法
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids) {
        log.info(ids.toString());
        for (Long id : ids) {
            dishService.removeById(id);
        }
        return R.success("删除菜品成功");
    }

    //启售停售方法
    @PostMapping("/status/{status}")
    public R<String> startDish(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            byId.setStatus(status);
            dishService.updateById(byId);
        }
        return R.success("修改成功");
    }

    //根据条件查询对应的数据 -手机端
    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish) {


        List<DishDTO> dishDtoList = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDTO>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        //条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        //添加条件 查询状态为1 启售状态的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDTO> dishDTOS = list.stream().map((item) -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);

            //获取分类id
            Long categoryId = item.getCategoryId();

            //再根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }

            //获取当前菜品id
            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();

            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);

            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            dishDTO.setFlavors(dishFlavorList);

            return dishDTO;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDTOS);
    }
}
